package cn.wolfcode.crm.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.wolfcode.crm.query.ChartQueryObject;
import cn.wolfcode.crm.service.IChartService;
import cn.wolfcode.crm.util.JSONUtil;
import cn.wolfcode.crm.util.MessageUtil;

@Controller
@RequestMapping("/chart")
public class ChartController {
	
	@Autowired
	private IChartService chartService;

	@RequestMapping("/list")
	public String list(@ModelAttribute("qo") ChartQueryObject qo, Model model) {
		model.addAttribute("list", chartService.queryChart(qo));
		return "chart/list";
	}
	
	@RequestMapping("queryBar")
    public String queryBar(@ModelAttribute("qo") ChartQueryObject qo, Model model) {
    	List<Map<String, Object>> list = chartService.queryChart(qo);
    	//['逍遥', 'bunny', '王尼玛']
    	List<Object> x = new ArrayList<>();
    	//[50, 30, 45]
    	List<Object> y = new ArrayList<>();
    	for (Map<String, Object> map : list) {
			x.add(map.get("groupType"));
			y.add(map.get("totalNumber"));
		}
    	model.addAttribute("groupType", MessageUtil.changMsg(qo));
    	model.addAttribute("x", JSONUtil.toJSONString(x));
    	model.addAttribute("y", JSONUtil.toJSONString(y));
        return "chart/bar";
    }

    @RequestMapping("queryPie")
    public String queryPie(@ModelAttribute("qo") ChartQueryObject qo, Model model) {
        //['admin','bunny','wangnima']
    	/*[
            {value:335, name:'admin'},
            {value:310, name:'bunny'},
            {value:234, name:'wangnima'}
          ]*/
    	List<Map<String, Object>> list = chartService.queryChart(qo);
    	List<Object> legend = new ArrayList<>();
    	List<Object> series = new ArrayList<>();
    	for (Map<String, Object> map : list) {
    		Object type = map.get("groupType");
    		legend.add(type);
			Map<String,Object> data = new HashMap<>();
			data.put("name", type);
			data.put("value", map.get("totalNumber"));
			series.add(data);
		}
    	model.addAttribute("groupType", MessageUtil.changMsg(qo));
    	model.addAttribute("legendDate", JSONUtil.toJSONString(legend));
    	model.addAttribute("seriesDate", JSONUtil.toJSONString(series));
        return "chart/pie";
    }
}
